package com.abe.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import org.xutils.common.util.DensityUtil;
import org.xutils.image.ImageOptions;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.abe.app.ManagerAPP;
import com.abe.config.SettingParam;
import com.abe.mvp.model.bean.SettingBean;
import com.abe.strengthtrainer.R;

import dalvik.system.DexFile;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressLint({ "SimpleDateFormat", "SdCardPath" })
@SuppressWarnings("deprecation")
public class NormalUtils {

	public static void hideBottomUIMenu(Activity activity) {
		// 保持布局状态
		int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
				| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
				| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
				| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
		if (Build.VERSION.SDK_INT >= 19) {
			uiOptions |= 0x00001000;
		} else {
			uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
		}
		activity.getWindow().getDecorView().setSystemUiVisibility(uiOptions);
	}

	/** 获取是否存在NavigationBar */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static boolean checkDeviceHasNavigationBar(Context context) {
		boolean hasNavigationBar = false;
		Resources rs = context.getResources();
		int id = rs
				.getIdentifier("config_showNavigationBar", "bool", "android");
		if (id > 0) {
			hasNavigationBar = rs.getBoolean(id);
		}
		try {
			Class systemPropertiesClass = Class
					.forName("android.os.SystemProperties");
			Method m = systemPropertiesClass.getMethod("get", String.class);
			String navBarOverride = (String) m.invoke(systemPropertiesClass,
					"qemu.hw.mainkeys");
			if ("1".equals(navBarOverride)) {
				hasNavigationBar = false;
			} else if ("0".equals(navBarOverride)) {
				hasNavigationBar = true;
			}
		} catch (Exception e) {

		}
		return hasNavigationBar;

	}

	/**
	 * 启动一个app
	 */
	public static void startAPP(Context context, String appPackageName) {
		Intent intent = context.getPackageManager().getLaunchIntentForPackage(
				appPackageName);
		context.startActivity(intent);
	}

	/** 设置应用语言类型 */
	public static void setAppLanguage() {
		Context context = ManagerAPP.getContext();
		SettingBean settingBean = SettingParam.getSettingBean();
		/** 默认简体中文 */
		String language = settingBean.getLanguage();
		/** 设置应用语言类型 */
		Resources resources = context.getResources();
		Configuration config = resources.getConfiguration();
		DisplayMetrics dm = resources.getDisplayMetrics();
		if (language.equals(SettingParam.LANGUAGE_KEY_CN)) {
			config.locale = Locale.SIMPLIFIED_CHINESE;
		} else if (language.equals(SettingParam.LANGUAGE_KEY_EN)) {
			config.locale = Locale.ENGLISH;
		}
		resources.updateConfiguration(config, dm);
	}
	
	/**设置锻炼语言*/
	public static void setExerciseLanguage() {
		Context context = ManagerAPP.getContext();
		/** 默认简体中文 */
		String language = (String) SPUtils.get(context,
				SettingParam.SP_LANGUAGE_KEY, SettingParam.LANGUAGE_KEY_CN);
		/** 设置应用语言类型 */
		Resources resources = context.getResources();
		Configuration config = resources.getConfiguration();
		DisplayMetrics dm = resources.getDisplayMetrics();
		if (language.equals(SettingParam.LANGUAGE_KEY_CN)) {
			config.locale = Locale.SIMPLIFIED_CHINESE;
		} else if (language.equals(SettingParam.LANGUAGE_KEY_EN)) {
			config.locale = Locale.ENGLISH;
		}
		resources.updateConfiguration(config, dm);
	}

	public static String getString(int id) {
		return ManagerAPP.getContext().getResources().getString(id);
	}

	/** 获取当前Activity截图 */
	public static Bitmap getShot(Activity activity) {
		/** 获取windows中最顶层的view */
		View view = activity.getWindow().getDecorView();
		Bitmap bitmap = view.getDrawingCache();
		view.destroyDrawingCache();
		return bitmap;
	}

	/** 获取当前Activity截图 */
	public static Bitmap getActivityShot(Activity activity) {
		/** 获取windows中最顶层的view */
		View view = activity.getWindow().getDecorView();
		view.buildDrawingCache();
		/** 获取状态栏高度 */
		Rect rect = new Rect();
		view.getWindowVisibleDisplayFrame(rect);
		int statusBarHeights = rect.top;
		Display display = activity.getWindowManager().getDefaultDisplay();
		/** 获取屏幕宽和高 */
		int widths = display.getWidth();
		int heights = display.getHeight();
		/** 允许当前窗口保存缓存信息 */
		view.setDrawingCacheEnabled(true);
		/** 去掉状态栏 */
		Bitmap bmp = Bitmap.createBitmap(view.getDrawingCache(), 0,
				statusBarHeights, widths, heights - statusBarHeights);
		/** 销毁缓存信息 */
		view.destroyDrawingCache();

		return bmp;
	}

	/**
	 * 发送本地广播
	 * 
	 * @param filterAction
	 *            过滤
	 * @param action
	 *            标识
	 * @param message
	 *            消息
	 * */
	public static void sendLocalBroadcast(String filterAction, String action,
			Bundle message) {

		if (filterAction == null) {
			ToastUtils.showShort(ManagerAPP.getContext(), "filterAction为NULL");
			return;
		}
		if (filterAction.equals("")) {
			ToastUtils.showShort(ManagerAPP.getContext(), "filterAction为空");
			return;
		}
		if (action == null) {
			ToastUtils.showShort(ManagerAPP.getContext(), "action为NULL");
			return;
		}
		if (action.equals("")) {
			ToastUtils.showShort(ManagerAPP.getContext(), "action为空");
			return;
		}

		Intent intent = new Intent();
		intent.setAction(filterAction);
		intent.putExtra("action", action);
		if (message == null) {
			message = new Bundle();
		}
		intent.putExtras(message);
		LocalBroadcastManager.getInstance(ManagerAPP.getContext())
				.sendBroadcast(intent);
	}

	/**
	 * 获取XUtils的ImageOptions
	 * 
	 * @return ImageOptions
	 */
	public static ImageOptions GetXUtilsImageOptions() {
		// 通过ImageOptions.Builder().set方法设置图片的属性
		ImageOptions imageOptions = new ImageOptions.Builder()
				.setSize(DensityUtil.dip2px(200), DensityUtil.dip2px(200))
				// .setRadius(DensityUtil.dip2px(5))
				// 如果ImageView的大小不是定义为wrap_content, 不要crop.
				// .setCrop(true)
				// 加载中或错误图片的ScaleType
				.setPlaceholderScaleType(ImageView.ScaleType.CENTER_CROP)
				.setImageScaleType(ImageView.ScaleType.CENTER_CROP)
				// 设置加载过程中的图片
				.setLoadingDrawableId(R.drawable.ic_launcher)
				// 设置加载失败后的图片
				.setFailureDrawableId(R.drawable.ic_launcher)
				// 设置使用缓存
				.setUseMemCache(true)
				// 设置支持gif
				.setIgnoreGif(false)
				// 设置显示圆形图片
				.setCircular(false).setSquare(false).build();

		return imageOptions;
	}

	public static List<String> getClassName(Context context, String packageName) {
		List<String> classNameList = new ArrayList<String>();
		try {

			DexFile df = new DexFile(context.getPackageCodePath());// 通过DexFile查找当前的APK中可执行文件
			Enumeration<String> enumeration = df.entries();// 获取df中的元素
															// 这里包含了所有可执行的类名
															// 该类名包含了包名+类名的方式
			while (enumeration.hasMoreElements()) {// 遍历
				String className = (String) enumeration.nextElement();

				if (className.contains(packageName)) {// 在当前所有可执行的类里面查找包含有该包名的所有类
					classNameList.add(className);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return classNameList;
	}

	/**
	 * @see service是否还在运行
	 */
	public boolean isServiceRunning(Context mContext, String className) {

		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(30);

		if (!(serviceList.size() > 0)) {
			return false;
		}

		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	/**
	 * @see 程序是否在前台运行
	 * 
	 * @return
	 */
	public static boolean isAppOnForeground(Context context) {
		// Returns a list of application processes that are running on the
		// device
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		String packageName = context.getPackageName();

		List<RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		if (appProcesses == null)
			return false;
		for (RunningAppProcessInfo appProcess : appProcesses) {
			// The name of the process that this object is associated with.
			if (appProcess.processName.equals(packageName)
					&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
				return true;
			}
		}
		return false;
	}

	/**
	 * @see 返回缩放比例
	 */
	public static float getScale(Context context) {
		DisplayMetrics displayMetrics = context.getResources()
				.getDisplayMetrics();
		float width = displayMetrics.widthPixels;
		float scale = width / 1280;
		return scale;
	}

	/**
	 * @see 保存错误信息到文件中
	 * 
	 * @param ex
	 * @return 返回文件名称,便于将文件传送到服务器
	 */
	public static String saveCrashInfo2File(String name, String errorcode) {
		// 用于格式化日期,作为日志文件名的一部分
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		StringBuffer sb = new StringBuffer();
		sb.append(errorcode);
		try {
			long timestamp = System.currentTimeMillis();
			String time = formatter.format(new Date());
			String fileName = name+"-" + time + "-" + timestamp + ".txt";
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				String path = "/sdcard/crash/";
				File dir = new File(path);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				FileOutputStream fos = new FileOutputStream(path + fileName);
				fos.write(sb.toString().getBytes());
				fos.close();
			}
			return fileName;
		} catch (Exception e) {

		}
		return null;
	}

	/**
	 * @see 快捷Message生成
	 * 
	 */
	public static Message getMessage(int what, Object obj) {
		Message msg = new Message();
		msg.what = what;
		msg.obj = obj;
		return msg;
	}

	public static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1) {
				hs = hs + "0" + stmp;
			} else {
				hs = hs + stmp;
			}
		}
		return hs;
	}

	/**
	 * @see SHA1 加密实例
	 */
	public static String encryptToSHA(String info) {
		byte[] digesta = null;
		try {
			// 得到一个SHA-1的消息摘要
			MessageDigest alga = MessageDigest.getInstance("SHA-1");
			// 添加要进行计算摘要的信息
			alga.update(info.getBytes());
			// 得到该摘要
			digesta = alga.digest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		// 将摘要转为字符串
		String rs = byte2hex(digesta);
		return rs;
	}

	/**
	 * @see double保留0位小数
	 */
	public static String KeepZeroDecimal(double x) {
		DecimalFormat df = new DecimalFormat("######0");
		return df.format(x);
	}

	/**
	 * @see double保留两位小数
	 */
	public static String KeepTwoDecimal(double x) {
		DecimalFormat df = new DecimalFormat("######0.00");
		return df.format(x);
	}

	/**
	 * @see 拨打电话方法
	 */
	public static void callPhone(Context context, String phone_num) {
		Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
				+ phone_num)); // 创建一个意图
		context.startActivity(intent);// 开始意图(及拨打电话)
	}

	/**
	 * @see 16位MD5加秘
	 */
	public static String md516(String password) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(password.getBytes());
		byte[] b = md.digest();

		StringBuffer buf = new StringBuffer("");
		for (int offset = 0; offset < b.length; offset++) {
			int i = b[offset];
			if (i < 0)
				i += 256;
			if (i < 16)
				buf.append("0");
			buf.append(Integer.toHexString(i));
		}

		String pwd = buf.toString().substring(8, 24);

		return pwd;
	}

	/**
	 * @see 32位MD5加秘
	 */
	public static String md532(String password) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(password.getBytes());
		byte[] b = md.digest();

		StringBuffer buf = new StringBuffer("");
		for (int offset = 0; offset < b.length; offset++) {
			int i = b[offset];
			if (i < 0)
				i += 256;
			if (i < 16)
				buf.append("0");
			buf.append(Integer.toHexString(i));
		}

		String pwd = buf.toString();

		return pwd;
	}

	/**
	 * @see map中取字符串
	 */
	@SuppressWarnings("rawtypes")
	public static String getStringFromMap(Map map, String key,
			String defaultValue) {
		String value = defaultValue;
		try {
			if (map != null) {
				if (map.containsKey(key)) {
					if (map.get(key) != null) {

						value = map.get(key).toString();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	/**
	 * @see 如果listItem报空指针异常，注意，list的item布局换为LinearLayout
	 */
	public static int setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return 0;
		}
		int totalHeight = 0;
		for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
		return params.height;
	}

	/**
	 * @see OOM_Image_Error
	 */
	public static Drawable readDrawable(Context context, int resId) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = context.getResources().openRawResource(resId);
		return new BitmapDrawable(BitmapFactory.decodeStream(is, null, opt));
	}

	/**
	 * @see InputStream转Drawable
	 */
	public static Drawable readDrawable(InputStream is) {
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		return new BitmapDrawable(BitmapFactory.decodeStream(is, null, opt));
	}

	/**
	 * @see 时间戳根据格式化规则转为时间
	 * @param rule
	 *            规则（例如：yyyy年MM月dd日 HH:mm）
	 * @param sjc
	 *            时间戳字符串
	 */
	/**
	 * 将时间戳 转为yyyy-MM-dd HH:mm:ss
	 * 
	 */
	public static String getTimeBySJC(String sjc, String rule) {
		SimpleDateFormat sdf1 = new SimpleDateFormat(rule);
		// 现在时间
		return "" + sdf1.format(new Date(Integer.parseInt(sjc) * 1000L));
	}

	/**
	 * @see 根据格式化规则获取当前时间
	 * @param rule
	 *            规则（例如：yyyy年MM月dd日 HH:mm）
	 */
	public static String getNowTimeByRule(String rule) {
		Date Now;
		String nowStr = null;
		SimpleDateFormat sdf = new SimpleDateFormat(rule);
		try {
			nowStr = getRequestUrlTime();
		} catch (ExecutionException e1) {
			e1.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		long ld = Long.parseLong(nowStr);
		Now = new Date(ld); // 转换为标准时间对象
		// 分别取得时间中的小时，分钟和秒，并输出
		Log.d("multicast", Now + ", " + Now.getHours() + "时" + Now.getMinutes()
				+ "分" + Now.getSeconds() + "秒");
		String UserTime = sdf.format(Now);
		return UserTime;
	}

	/**
	 * @see 获取当前网络时间
	 */
	public static String getRequestUrlTime() throws Exception,
			ExecutionException {
		FutureTask<String> task = new FutureTask<String>(
				new Callable<String>() {
					@Override
					public String call() throws Exception {

						URL url;
						try {
							url = new URL("http://www.baidu.com");
							URLConnection uc = url.openConnection();// 生成连接对象
							uc.connect(); // 发出连接
							long ld = uc.getDate(); // 取得网站日期时间
							return ld + "";
						} catch (MalformedURLException e) {
							e.printStackTrace();
						} // 取得资源对象
						catch (IOException e) {
							e.printStackTrace();
						}
						return null;
					}
				});
		new Thread(task).start();
		return task.get();
	}

	/**
	 * @see 防止重复点击
	 */
	private static long lastClickTime;

	public synchronized static boolean isFastClick() {
		long time = System.currentTimeMillis();
		if (time - lastClickTime < 1000) {
			return true;
		}
		lastClickTime = time;
		return false;
	}
}
